package com.kuangstudy.service.category;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuangstudy.constant.RedisConstants;
import com.kuangstudy.entity.Category;
import com.kuangstudy.mapper.CategoryMapper;
import io.rebloom.client.Client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年09月20日 10:48:00
 * @Description
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private Client rebloomClient;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 启动初始化bloomfilter的课程信息分类
     * todo 后续增加了新分类：
     *    - 1、定时任务5分钟做同步
     *    - 2 再写db同时往bloomfilter中再写一份
     *    - 3 启动服务做同步（太low了）
     */
    @PostConstruct
    private void initBloomData() {
        if (!redisTemplate.hasKey(RedisConstants.REDIS_BLOOM_COURSE_CATEGORY)) {
            List<Long> categoryList = this.findCateGoryPid();
            if (!CollectionUtils.isEmpty(categoryList)) {
                // 把对应的一级分类的id放入到布隆过滤器中
                String[] ids = new String[categoryList.size()];
                for (int i = 0; i < categoryList.size(); i++) {
                    ids[i] = categoryList.get(i).toString();
                }
                // bf.madd 1 2 3 4 5
                rebloomClient.addMulti(RedisConstants.REDIS_BLOOM_COURSE_CATEGORY, ids);
            }
        }
    }


    /**
     * 根据pid查询课程分类的信息
     *
     * @param cid
     * @return
     */
    @Override
    public List<Category> findCategorysByPid(Integer cid) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("pid", cid);
        List<Category> categoryList = this.list(queryWrapper);
        return categoryList;
    }


    /**
     * 查询课程表中所有的pid
     *
     * @return
     */
    @Override
    public List<Long> findCateGoryPid() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("pid");
        queryWrapper.eq("status", 1);
        queryWrapper.groupBy("pid");
        List<Category> categoryList = this.list(queryWrapper);
        List<Long> longList = categoryList.stream().map(Category::getPid).collect(Collectors.toList());
        return longList;
    }

}
